package it.danghongphat.business;

import it.danghongphat.database.DatabaseManager;
import it.danghongphat.object.Material;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public class MaterialBusiness {
	AbstractTableModel model;
	String headers[];
	DatabaseManager databaseManager=new DatabaseManager();
	public MaterialBusiness(AbstractTableModel model) {
		this.model=model;
	}
	public boolean insert(Material m){
		String query = "INSERT INTO hanghoa VALUES ( '"
				+ m.getMah() + "', '"
				+ m.getTenh() + "', '"
				+ m.getManh() + "', '"
				+ m.getDvt() + "', '"
				+ m.getDb() + "')"
				;
		if(databaseManager.excuteQuery(query)){
			databaseManager.closeConnection();
			return true;
		}
		else
			return false;
	}
	public boolean update(Material m){
		String query = "UPDATE HANGHOA SET mah = '"
				+ m.getMah() + "', tenh = '"
				+ m.getTenh() + "', man = '" 
				+ m.getManh()  + "', dvt = '"
				+ m.getDvt()  + "', db = '"
				+ m.getDb()  + "' "
				+ " WHERE mah = '" + m.getMah() + "'"	;
		if(databaseManager.excuteQuery(query)){
			databaseManager.closeConnection();
			return true;
		}
		else
			return false;
	}
	public boolean delete(Material m){
		String query = "delete from hanghoa where mah = '" + m.getMah() + "'"	;
		if(databaseManager.excuteQuery(query)){
			databaseManager.closeConnection();
			return true;
		}
		else
			return false;
	}
	public List<Material> LoadListMaterialList (){
		 List<Material>lst =new ArrayList<>();
		try {
			ResultSet rs = databaseManager.getResultSet("SELECT * FROM HANGHOA order by man ASC");
			ResultSetMetaData meta = rs.getMetaData();
		    headers = new String[meta.getColumnCount()];
			for (int h = 1; h <= meta.getColumnCount(); h++) {
				  headers[h - 1] = meta.getColumnName(h);
			}
			while (rs.next()) {
		        Material material=new Material();
		        material.setMah(rs.getString(1));
		        material.setTenh(rs.getString(2));
		        material.setManh(rs.getString(3));
		        material.setDvt(rs.getString(4));
		        material.setDb(rs.getString(5));
		        lst.add(material);
		       }
				model.fireTableDataChanged();
		        databaseManager.closeConnection();
		   } catch (SQLException e) {
			e.printStackTrace();
		}
		 return lst;
		}
	public String[] getHeader(){
		return headers;
	}
}
